import re

from rest_framework.exceptions import ValidationError
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from common.models import District, IndustryCategory


class DistrictSimpleSerializer(ModelSerializer):

    class Meta:
        model = District
        exclude = ('parent', 'is_hot')


class DistrictDetailSerialzier(ModelSerializer):
    children = SerializerMethodField()

    @staticmethod
    def get_children(district):
        # queryset = District.objects.filter(parent=district.id)
        return DistrictSimpleSerializer(district.children, many=True).data

    class Meta:
        model = District
        exclude = ('parent', )


class DistrictSerializer(ModelSerializer):

    def validate(self, attrs):
        if re.fullmatch(r'[1-9]\d{5}', str(attrs['id'])) is None:
            raise ValidationError('无效的行政区域编号')
        if re.fullmatch(r'[\u4e00-\u9fa5]{2,8}', attrs['name']) is None:
            raise ValidationError('无效的行政区域名称')
        return attrs

    class Meta:
        model = District
        fields = '__all__'


class IndustryCategorySerializer(ModelSerializer):

    class Meta:
        model = IndustryCategory
        exclude = ('insert_time', 'delete_time', 'update_time', 'is_deleted', 'memo')
